//
//  YWInspectionDetailViewController.m
//  maintain
//
//  Created by Kyo on 16/5/26.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import "YWInspectionDetailViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "NSDate+Additions.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "UIView+Extension.h"
#import "YWDictMaintenanceType.h"
#import "YWInspectionMissionModel.h"
#import "YWInspectionMissionManager.h"
#import "YWInspectionLineRecord.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"
#import "YWQrcodeManager.h"
#import "YWEquipmentManager.h"
#import "YWInspectionRecordDetailViewController.h"
#import "YWNoQrcodeRights.h"

#import "YWInspectionMisionDetailCell.h"
#import "YWInspectionTimeLineCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "Masonry.h"
#import "MJRefresh.h"

#import "YWModifyInspectionMissionTableViewController.h"
#import "MBProgressHUD.h"
#import "FTPopOverMenu.h"
#import "YWInspectionReplyTableViewController.h"
#import "YWNoQrcodeSelectLocationTableViewController.h"
#import "YWReply.h"
#import "YWReplyManager.h"

#import "YWSelectAtUserTableViewController.h"
#import "YWObserverTableViewController.h"
#import "YWObserveTableViewCell.h"
#import "YWNewReplyTableViewCell.h"
#import "YWMeterReadingDetailRecordCell.h"

@interface YWInspectionDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,YWSelectAtUserTableViewDelegate>{
    NSString *replyContent;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *sourceDatas;
@property (nonatomic, strong) NSArray *timeLineDataArray;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UIButton *scanButton;
@property (nonatomic, strong) UIButton *noScanButton;
@property (nonatomic, strong) UIButton *doButton;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, assign) BOOL needReload;

@property (nonatomic, strong) NSArray *replyArray;//评论数组
@property (nonatomic, strong) UIView *replyView;//回复栏
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@end

@implementation YWInspectionDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"inspectionDetail", nil);
    self.view.backgroundColor = [UIColor customBackgroudColor];
    if (self.inspectionMission.creator.uniqueId == [YWLoginTool loginUser].uniqueId) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"• • • " style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButtonEvent:event:)];
    }
    
    [self setupNotifications];
    [self setupTableView];
    [self.navigationController.view addSubview:self.replyView];
    YWWeakSelf(weakSelf);
    __block NSInteger needReload = 0;
    if (self.inspectionMission.inspectionMissionId) {
        [[YWInspectionMissionManager shareManager] requestInspectionMissionInfo:self.inspectionMission.inspectionMissionId complete:^(BOOL success) {
            //刷新数据
            [weakSelf loadTimeLineData];
            BOOL existEquipment = [[YWInspectionMissionManager shareManager] isExistEquipmentWithLineId:weakSelf.inspectionMission.inspectionLine.inspectionLineId];
            if (weakSelf.inspectionMission.inspectionLine.inspectionLineId!=0 && (existEquipment == NO || weakSelf.inspectionMission.inspectionLine.intervalMinute==0 || (weakSelf.inspectionMission.inspectionLine.locationRels.count==0 && weakSelf.inspectionMission.inspectionLine.equipments.count==0))) {
                [[YWInspectionMissionManager shareManager] requestInspectionLineWithInspectionLineId:weakSelf.inspectionMission.inspectionLine.inspectionLineId Complete:^(YWInspectionLineModel *inspectionLine) {
                    if (inspectionLine) {
                        weakSelf.inspectionMission.inspectionLine = inspectionLine;
                        needReload += 1;
                        if (needReload == 2) {
                            [weakSelf.tableView reloadData];
                        }
                    }
                }];
            }
        }];
        //请求评论
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(self.inspectionMission.inspectionMissionId).stringValue type:YWReplyRelationTypeInspection WithComplete:^(BOOL success) {
            needReload += 1;
            if (needReload == 2) {
                [weakSelf.tableView reloadData];
            }
        }];
    }
    if (self.notFromInspectionMissionVC) {
        [[YWInspectionMissionManager shareManager] requestInspectionMissionWithMissionId:weakSelf.inspectionMission.inspectionMissionId Complete:^(YWInspectionMissionModel *inspectionMission) {
            if (inspectionMission) {
                YWInspectionMissionModel *mission = [[YWInspectionMissionManager shareManager]inspectionMissionWithMissionId:inspectionMission.inspectionMissionId];
                weakSelf.inspectionMission = mission;
            }
            [[YWInspectionMissionManager shareManager] requestInspectionLineWithInspectionLineId:weakSelf.inspectionMission.inspectionLine.inspectionLineId Complete:^(YWInspectionLineModel *inspectionLine) {
                if (inspectionLine) {
                    weakSelf.inspectionMission.inspectionLine = inspectionLine;
                    [weakSelf.tableView reloadData];
                }
            }];
        }];
    }
}

- (void)setupTableView{
    self.page = 1;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    //有刷新加载时，这句代码要放在刷新下面，不然每次进入界面都是刷新后才有数据
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KbottomViewH)];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshInspectionMissionTimeLineView) name:KRefreshInspectionTimeLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshInspectionMissionTimeLineView) name:KRefreshInspectionLatestRecordNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshInspectionMissionTimeLineView) name:KRefreshModifyInspectionMissionNotification object:nil];
}

- (void)refreshInspectionMissionTimeLineView{
    _needReload = YES;
}

- (void)refreshTop{
    self.page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    if (refreshType == YWTableViewFreshTypeUp) {
        self.page++;
    }
    YWWeakSelf(weakSelf);
    [[YWInspectionMissionManager shareManager] requestInspectionLineRecordWithPage:self.page pageSize:10 inspectionMissionId:_inspectionMission.inspectionMissionId?:0 inspectionLineId:_inspectionMission.inspectionLine.inspectionLineId?:0 WithComplete:^(BOOL success) {
        if (refreshType == YWTableViewFreshTypeDown) {
            [weakSelf.tableView.mj_header endRefreshing];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.tableView.mj_header removeFromSuperview];
            });
            //刷新数据
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSArray *array = [[YWInspectionMissionManager shareManager] timeLineViewDataWithInspectionMission:self.inspectionMission orLineRecord:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.timeLineDataArray = array;
                    [self.tableView reloadData];
                });
            });
        }else {
            [weakSelf.tableView.mj_footer endRefreshing];
            //刷新数据
            _sourceDatas = nil;
            [self.tableView reloadData];
        }
    }];
}

//数据源
-(NSMutableArray *)sourceDatas{
    if (!_sourceDatas) {
        _sourceDatas = [NSMutableArray array];
        [_sourceDatas addObjectsFromArray:[[YWInspectionMissionManager shareManager]inspectionLineRecordWithInspectionMission:_inspectionMission page:self.page]];
        //设置已读状态
//        [[YWInspectionMissionManager shareManager] updateReadStatusWithInspectionMissionId:_inspectionMission.inspectionMissionId];
    }
    return _sourceDatas;
}

- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_inspectionMission.inspectionMissionId andRelationType:YWReplyRelationTypeInspection];
        _replyArray = commentArray;
    }
    return _replyArray;
}

- (NSArray *)timeLineDataArray{
    if (!_timeLineDataArray) {
        _timeLineDataArray = [NSArray array];
    }
    return _timeLineDataArray;
}

- (void)loadTimeLineData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [[YWInspectionMissionManager shareManager] timeLineViewDataWithInspectionMission:self.inspectionMission orLineRecord:nil];
        
        NSArray *recordArray = [[YWInspectionMissionManager shareManager]inspectionLineRecordWithInspectionMission:_inspectionMission page:self.page];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.sourceDatas removeAllObjects];
            if (recordArray) {
                [_sourceDatas addObjectsFromArray:recordArray];
            }
            self.timeLineDataArray = array;
            [self.tableView reloadData];
        });
    });
}

- (UITableView *)tableView{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        
        [tableView registerClass:[YWInspectionMisionDetailCell class] forCellReuseIdentifier:YWInspectionMisionDetailCellIdentifier];
        [tableView registerClass:[YWInspectionTimeLineCell class] forCellReuseIdentifier:inspectionTimeLineCellIdentifier];
        [tableView registerClass:[YWObserveTableViewCell class] forCellReuseIdentifier:YWObserveTableViewCellIdentifier];
        [tableView registerClass:[YWNewReplyTableViewCell class] forCellReuseIdentifier:YWNewReplyTableViewCellIdetifer];
        [tableView registerClass:[YWMeterReadingDetailRecordCell class] forCellReuseIdentifier:YWMeterReadingDetailRecordCellIdentifier];
        tableView.delegate = self;
        tableView.dataSource = self;
        _tableView = tableView;
        
        if (!self.isFromMatchMissionVC) {
            if ([YWCommonTool containSelfInHandlers:_inspectionMission.executors]) {
                [self.view addSubview:self.noScanButton];
                [self.view addSubview:self.scanButton];
                _tableView.height -= KbottomViewH;
            }
        }else{
            [self.view addSubview:self.doButton];
            _tableView.height -= KbottomViewH;
        }
        
    }
    return _tableView;
}
#pragma mark - UITableViewDataSource mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section==0) {
//        if (indexPath.row==0) {
//            return [tableView fd_heightForCellWithIdentifier:YWInspectionMisionDetailCellIdentifier cacheByIndexPath:indexPath configuration:^(YWInspectionMisionDetailCell *cell) {
//                cell.fd_enforceFrameLayout = NO;
//                cell.inspectionMission = self.inspectionMission;
//            }];
//        }else{
//            return [tableView fd_heightForCellWithIdentifier:inspectionTimeLineCellIdentifier cacheByIndexPath:indexPath configuration:^(YWInspectionTimeLineCell *cell) {
//                cell.fd_enforceFrameLayout = NO;
//                cell.dicData = self.timeLineDataArray[indexPath.row-1];
//            }];
//        }
//    }else{
//        return 44;
//    }
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 3+self.sourceDatas.count;//self.sourceDatas.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else if (section == 1){
        if (self.replyArray.count>0) {
            return [self.replyArray count] + 2;//参与人+“评论”
        }else{
            return 1;
        }
    }else if (section == 2){
        return self.timeLineDataArray.count;
    }else{
        return self.sourceDatas.count>=section-3 ? [self.sourceDatas[section-3] count] : 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        YWInspectionMisionDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:YWInspectionMisionDetailCellIdentifier];
        cell.fd_enforceFrameLayout = NO;
        cell.inspectionMission = self.inspectionMission;
        return cell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            YWObserveTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWObserveTableViewCellIdentifier];
            cell.inspectionMission = _inspectionMission;//参与人cell
            return cell;
        }else{
            if (indexPath.row == 1) {
                YWMeterReadingDetailRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMeterReadingDetailRecordCellIdentifier];
                NSString *count;
                if (self.replyArray.count>0) {
                    count = [NSString stringWithFormat:@"(%ld)",(unsigned long)self.replyArray.count];
                }else{
                    count = @"";
                }
                NSString *replyText = [NSString stringWithFormat:@"评论%@:",count];
                cell.contentLabel.text = replyText;
                cell.contentLabel.textColor = [UIColor customTextGrayColor];
                return cell;
            }
            YWNewReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNewReplyTableViewCellIdetifer];
            YWReply *reply = self.replyArray[indexPath.row-2];
            cell.reply = reply;
            return cell;
        }
    }else if (indexPath.section == 2){
        YWInspectionTimeLineCell *cell =[tableView dequeueReusableCellWithIdentifier:inspectionTimeLineCellIdentifier];
        cell.dicData = self.timeLineDataArray[indexPath.row];
        return cell;
    }else{
        static NSString *identifier = @"YWInspectionDetailViewControllerCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        YWInspectionLineRecord *lineRecord = nil;
        if (self.sourceDatas.count >= indexPath.section-3) {
            lineRecord = [self.sourceDatas[indexPath.section-3] count]-1 >= indexPath.row ? self.sourceDatas[indexPath.section-3][indexPath.row] : nil;
        }
        NSString *startTime = [YWCommonTool showTime:lineRecord.startTime/1000 andFormatter:KTimeFormatShortTime];
        NSString *endTime = [YWCommonTool showTime:lineRecord.endTime/1000 andFormatter:KTimeFormatShortTime];
        NSString *result = @"";
        if (lineRecord.result == YWInspectionLineRecordResultFinishAndNormal){
            result = NSLocalizedString(@"hasFinished", nil);//@"已完成";
            cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
        }else if (lineRecord.result == YWInspectionLineRecordResultUnfinishAndTrouble) {
            result = NSLocalizedString(@"unFinishedAndTrouble", nil);//@"未完成(有报障)";
            cell.detailTextLabel.textColor = [UIColor customRedColor];
        }else if (lineRecord.result == YWInspectionLineRecordResultFinishAndTrouble){
            result = NSLocalizedString(@"hasFinishedAndTrouble", nil);//@"已完成(有报障)";
            cell.detailTextLabel.textColor = [UIColor customRedColor];
        }else if (lineRecord.result == YWInspectionLineRecordResultUnfinishAndNormal) {
            result = NSLocalizedString(@"unFinished", nil);//@"未完成";
            cell.detailTextLabel.textColor = [UIColor blackColor];
        }else{
            result = NSLocalizedString(@"noManToInspection", nil);//@"无人巡查";
            cell.detailTextLabel.textColor = [UIColor customTextGrayColor];
        }
        cell.detailTextLabel.text = result;
        cell.textLabel.text = [NSString stringWithFormat:@"%@-%@",startTime,endTime];
        return cell;
    }
    
}

-(NSString *)tableViewHeadTxt:(NSInteger)section{
    YWInspectionLineRecord *lineRecord = nil;
    if (self.sourceDatas.count - 1 >= section) {
        lineRecord = [self.sourceDatas[section] count] >0 ? self.sourceDatas[section][0] : nil;
    }
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:lineRecord.startTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString *timeString = [NSString stringWithFormat:@"%@ %@",[YWCommonTool showChineseFormatterDate:lineRecord.startTime/1000],weekStr];
//    YWHandler *patrolMan = PatrollineRecord.patrolMan;
//    NSString *headText =[NSString stringWithFormat:@"%@  %@",patrolMan.userName?:@"",timeString];
//    headText = [NSString stringWithFormat:@"%@\n%@",self.keepWatchMission.patrolLine.patrolLineName,headText];
    return lineRecord!=nil?timeString:@"";
}

#pragma mark - UITableViewDataDelegate
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section>2) {
        return kLabelH+10;
    }else{
        return 0.0;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.sourceDatas.count>0 && section>=3) {
        static NSString* HeaderIdentifier = @"YWInspectionDetailViewControllerForHeaderInSection";
        
        UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
        if (headerView == nil) {
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
            UILabel* label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor customTextGrayColor];
            label.tag = 1006;
            label.numberOfLines = 0;
            label.font = KSmallContentFont;
            [headerView addSubview:label];
        }
        NSString *headText = [self tableViewHeadTxt:section-3];
        UILabel* label = [headerView viewWithTag:1006];
        label.text = headText;
        label.frame = CGRectMake(15, 5, SCREEN_WIDTH - 2 * 15, kLabelH);
        
        return headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 23;
    }else{
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section!=0) {
        return nil;
    }
    static NSString* HeaderIdentifier = @"YWCirculatonDetailVCForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor whiteColor];
        UIView *line = [[UIView alloc] init];
        line.frame = CGRectMake(0, 23, SCREEN_WIDTH, 1);
        line.backgroundColor = [UIColor customLineColor];
        [headerView addSubview:line];
        //评论
        UILabel *replyLabel = [[UILabel alloc] init];
        replyLabel.textAlignment = NSTextAlignmentLeft;
        replyLabel.textColor = [UIColor customTextGrayColor];
        replyLabel.tag = 2006;
        replyLabel.font = KSmallContentFont;
        replyLabel.userInteractionEnabled = YES;
        [replyLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyLabel];
        
        UIImageView *replyImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"remind_replyIcon"]];
        replyImageView.tag = 2006;
        replyImageView.userInteractionEnabled = YES;
        [replyImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleReplyLabelTapEvent:)]];
        [headerView addSubview:replyImageView];
        
        [replyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(line.mas_top);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(replyImageView.mas_top);
            make.left.mas_equalTo(replyImageView.mas_right).offset(8);
            make.right.mas_equalTo(headerView.mas_right).offset(-8);
            make.bottom.mas_equalTo(replyImageView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        //参与者
        UILabel *observerLabel = [[UILabel alloc] init];
        observerLabel.textAlignment = NSTextAlignmentLeft;
        observerLabel.textColor = [UIColor customTextGrayColor];
        observerLabel.tag = 2007;
        observerLabel.font = KSmallContentFont;
        observerLabel.userInteractionEnabled = YES;
        [observerLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerLabel];
        
        UIImageView *observerView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"common_invite"]];
        observerView.tag = 2007;
        observerView.userInteractionEnabled = YES;
        [observerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleObserverLabelTapEvent:)]];
        [headerView addSubview:observerView];
        
        [observerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(line.mas_top);
            make.width.mas_equalTo(@23);
            make.height.mas_equalTo(@23);
        }];
        [observerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(observerView.mas_top);
            make.left.mas_equalTo(observerView.mas_right).offset(8);
            make.right.mas_equalTo(replyImageView.mas_left).offset(-8);
            make.bottom.mas_equalTo(observerView.mas_bottom);
            make.width.mas_lessThanOrEqualTo(@90);
        }];
        
    }
    UILabel* label = [headerView viewWithTag:2006];
    label.text = NSLocalizedString(@"comment", nil);//@"评论";
    
    //参与者
    label = [headerView viewWithTag:2007];
    label.text = NSLocalizedString(@"invitation", nil);//@"邀请";
    return headerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0 && indexPath.row==0) {
        YWInspectionReplyTableViewController *inspectionReplyVC = [[YWInspectionReplyTableViewController alloc] init];
        inspectionReplyVC.inspectionMission = self.inspectionMission;
        [self.navigationController pushViewController:inspectionReplyVC animated:YES];
    }else if (indexPath.section>=3) {
        YWInspectionRecordDetailViewController *detailRecordVC = [[YWInspectionRecordDetailViewController alloc] init];
        YWInspectionLineRecord *lineRecord = self.sourceDatas[indexPath.section-3][indexPath.row];
        detailRecordVC.lineRecord = lineRecord;
        [self.navigationController pushViewController:detailRecordVC animated:YES];
    }
}


- (UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        //[scanButton setImage:[UIImage imageNamed:@"inspection_normal"] forState:UIControlStateNormal];
        //scanButton.layer.masksToBounds = YES;
        [button setTitle:NSLocalizedString(@"scanQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4*3, KbottomViewH);
        _scanButton = button;
    }
    return _scanButton;
}
- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:NSLocalizedString(@"noQrcode", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, SCREEN_HEIGHT-64-KbottomViewH, SCREEN_WIDTH/4, KbottomViewH);
        _noScanButton = button;
    }
    return _noScanButton;
}

- (UIButton *)doButton{
    if (!_doButton) {
        UIButton* doButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [doButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [doButton setBackgroundColor:[UIColor customBlueColor]];
        [doButton setTitle:NSLocalizedString(@"doMission", nil) forState:UIControlStateNormal];
        [doButton addTarget:self action:@selector(handleDoBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        doButton.frame = CGRectMake(0, SCREEN_HEIGHT-64-kButtonH, SCREEN_WIDTH, kButtonH);
        _doButton = doButton;
    }
    return _doButton;
}

- (void)handleDoBtnEvent:(id)sender{
    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:self.inspectionMission];
    __block YWInspectionLineRecord *looperRecord = [[YWInspectionMissionManager shareManager] latestInspectionLineRecordUniqueTag:uniqueTag];
    
    if (looperRecord && looperRecord.result >= YWInspectionLineRecordResultFinishAndTrouble) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"hasInspectionThisMoment", nil)];
        return;
    }
    BOOL isFromLedger = (self.qrCodeId||self.locationId) ? YES : NO;
    [[YWInspectionMissionManager shareManager] qrcodeSuccessWithEquipmentInspection:self.inspectionMission qrcodeId:self.qrCodeId noQrcodeLocationId:self.locationId uniqueTag:uniqueTag wReader:self isFromLedger:isFromLedger];
}

- (void)handleNoScanBtnEvent:(id)sender{
    NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeInspectionKey] integerValue];
    if (value==1) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"cantDoMissionWithoutPermission", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self doInspectionMissionWithScanOrNoScan:NO];
    }
}

- (void)clickScanBtnEvent:(id)sender{
    [self doInspectionMissionWithScanOrNoScan:YES];
}

- (void)doInspectionMissionWithScanOrNoScan:(BOOL)scan{
    YWWeakSelf(weakSelf);
    YWInspectionMissionModel *inspectionMission = weakSelf.inspectionMission;
    
    YWInspectionJudgeType judgeType = [[YWInspectionMissionManager shareManager] judgeTypeWithMission:inspectionMission];
    if (judgeType != YWInspectionJudgeTypeMatch) {
        [YWCommonTool showTextHUDWithContent:[[YWInspectionMissionManager shareManager] typeNameWithJudgeType:judgeType]];
        return;
    }
    
    NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:inspectionMission];
    YWInspectionLineRecord *looperRecord = [[YWInspectionMissionManager shareManager] latestInspectionLineRecordUniqueTag:uniqueTag];
    
    if (looperRecord && looperRecord.result >= YWInspectionLineRecordResultFinishAndTrouble) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"hasInspectionThisMoment", nil)];
        return;
    }
    if (scan) {
        [[YWQrcodeManager shareManager] clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                [[YWInspectionMissionManager shareManager] qrcodeSuccessWithEquipmentInspection:inspectionMission qrcodeId:qrcodeId noQrcodeLocationId:0 uniqueTag:uniqueTag wReader:qrCodeReaderViewController isFromLedger:NO];
                //            }];
            });
        }];
    }else{
        YWNoQrcodeSelectLocationTableViewController *noQrcodeSlecetLocationVC = [[YWNoQrcodeSelectLocationTableViewController alloc] init];
        __weak __typeof(&*noQrcodeSlecetLocationVC) weakNoQrcodeSlecetLocationVC = noQrcodeSlecetLocationVC;
        noQrcodeSlecetLocationVC.maintenanceType = YWMaintenanceTypePatrol;
        noQrcodeSlecetLocationVC.isDoTempMission = NO;
        noQrcodeSlecetLocationVC.doMissionBlock = ^(NSInteger locationId) {
            __strong __typeof(&*weakNoQrcodeSlecetLocationVC) strongNoQrcodeSlecetLocationVC = weakNoQrcodeSlecetLocationVC;
            NSString *uniqueTag = [YWCommonTool uniqueTagWithMission:inspectionMission];
            [[YWInspectionMissionManager shareManager] qrcodeSuccessWithEquipmentInspection:inspectionMission qrcodeId:nil noQrcodeLocationId:locationId uniqueTag:uniqueTag wReader:strongNoQrcodeSlecetLocationVC isFromLedger:YES];
        };
        noQrcodeSlecetLocationVC.lineId = inspectionMission.inspectionLine.inspectionLineId;
        noQrcodeSlecetLocationVC.isKeepWatch = NO;
        noQrcodeSlecetLocationVC.isEquipmentLine = YES;
        [self.navigationController pushViewController:noQrcodeSlecetLocationVC animated:YES];
    }
    
}

- (void)clickRightBarButtonEvent:(UIBarButtonItem *)sender event:(UIEvent *)event{
    [FTPopOverMenu showFromEvent:event
                        withMenu:@[NSLocalizedString(@"modify", ni),NSLocalizedString(@"delete", nil)]
                  imageNameArray:@[@"menu_edit",@"menu_delete"]
                       doneBlock:^(NSInteger selectedIndex) {
                           if (selectedIndex==0) {
                               YWModifyInspectionMissionTableViewController *modifyInspectionVC = [[YWModifyInspectionMissionTableViewController alloc] init];
                               modifyInspectionVC.inspectionMission = self.inspectionMission;
                               [self.navigationController pushViewController:modifyInspectionVC animated:YES];
                           }else{
                               UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToDelete", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
                               [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
                               [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                   [self.HUD show:YES];
                                   [[YWInspectionMissionManager shareManager] requestDeleteInspectionMission:self.inspectionMission.inspectionMissionId completeBlock:^(BOOL success) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           [self.HUD hide:YES];
                                           if (success) {
                                               [self.navigationController popViewControllerAnimated:YES];
                                           }
                                       });
                                   }];
                               }]];
                               [self presentViewController:alert animated:YES completion:nil];
                               
                           }
                       } dismissBlock:nil];
}

- (MBProgressHUD*)HUD{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)handleReplyLabelTapEvent:(id)sender{
    [self.textField becomeFirstResponder];
}

- (void)handleObserverLabelTapEvent:(id)sender{
    YWObserverTableViewController *observerVC = [[YWObserverTableViewController alloc] init];
    observerVC.creaters = self.inspectionMission.creator?@[self.inspectionMission.creator]:nil;
    observerVC.executors = self.inspectionMission.executors;
    observerVC.observers = self.inspectionMission.observers;
    observerVC.relationId = [@(self.inspectionMission.inspectionMissionId) stringValue];
    observerVC.type = YWReplyRelationTypeDetectAndUpkeep;
    [self.navigationController pushViewController:observerVC animated:YES];
}


- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        _replyView.hidden = YES;
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-40-15, 40)];
    self.textField.placeholder = NSLocalizedString(@"reply", nil);//@"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.textField.delegate = self;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, 40, 40);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
    selectAtUserVC.delegate = self;
    NSMutableArray *allUser = [NSMutableArray array];
    //创建人
    if (self.inspectionMission.creator) {
        [allUser addObject:self.inspectionMission.creator];
    }
    //执行人
    [allUser addObjectsFromArray:self.inspectionMission.executors];
    //observer
    [allUser addObjectsFromArray:self.inspectionMission.observers];
    selectAtUserVC.allUserArray = allUser;
    [self.navigationController pushViewController:selectAtUserVC animated:YES];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeReplyContent", nil)];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replyContentLengthCannotMoreThan100", nil)];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    replyContent = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replySucceed", nil)];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _inspectionMission.inspectionMissionId;
    reply.relationType = YWReplyRelationTypeInspection;
    reply.content = replyContent;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

- (void)addObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:self.inspectionMission.observers];
        [tempArray addObject:handler];
        self.inspectionMission.observers = [NSArray arrayWithArray:tempArray];
    }
}

- (void)deleteObserver:(NSNotification*)noti{
    if ([noti.object isKindOfClass:[YWHandler class]]) {
        YWHandler* handler = (YWHandler*)noti.object;
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[self.inspectionMission.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            NSMutableArray *tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:self.inspectionMission.observers];
            [tempArray removeObject:handler];
            self.inspectionMission.observers = [NSArray arrayWithArray:tempArray];
        }
    }
}

#pragma mark ----- 有关键盘
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.replyView.hidden = YES;
    [self.textField endEditing:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_needReload) {
        _needReload = NO;
        [self loadTimeLineData];
    }
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addObserver:) name:KPostMissionAddObserverNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteObserver:) name:KPostMissionDeleteObserverNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT;
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.navigationController.view endEditing:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
